package le.grand;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

public class FileParser {
	private static final SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");

	String[] splits;

	Date date;

	int index;

	Map<String, HotelInfo> hotels = new HashMap<>();
	HotelInfo currentHotel;

	public void parse(File f) throws Exception {
		String fileContent = FileUtils.readFileToString(f);
		splits = StringUtils.split(fileContent, "\n\r");
		for (int i = 0; i < splits.length; i++) {
			splits[i] = splits[i].trim();
		}

		int firstDateLine = firstDateLine(splits);
		index = firstDateLine+2;
		String dateStr = splits[firstDateLine].substring(0, 12).trim();
		Date date = sdf.parse(dateStr);

		String hotel = null;
		while ((hotel = nextHotel()) != null) {
			System.out.println("New Hotel: "+hotel);
			currentHotel = getHotelInfo(hotel);
			while(readReservationLine()) {
				
			}
		}

	}

	public HotelInfo getHotelInfo(String hotelName) {
		HotelInfo hotelInfo = hotels.get(hotelName);
		if(hotelInfo == null) {
			hotelInfo = new HotelInfo(hotelName);
			hotels.put(hotelName, hotelInfo);
		}
		return hotelInfo;
	}
	
	private boolean readReservationLine() {
		String l = splits[index];
		if(l.startsWith("Total passengers for Hotel:")) {
			return false;
		}
		String[] tokens = StringUtils.split(l, " ");
		if (StringUtils.isNumeric(tokens[0])) {
			ReservationInfo ri = new ReservationInfo();
			Integer reservationNumber = Integer.parseInt(tokens[0]);
			ri.setReservationNumber(reservationNumber);
			int nextNumericToken = getNextNumericToken(1, tokens);
			Integer numOfPassengers = Integer.parseInt(tokens[nextNumericToken]);
			ri.setNumOfPassengers(numOfPassengers);
			currentHotel.addReservation(ri);
		}
		index++;
		return true;
	}
	
	private int getNextNumericToken(int startIndex, String[] tokens) {
		for (int i = startIndex; i < tokens.length; i++) {
			if(StringUtils.isNumeric(tokens[i])) {
				return i;
			}
		}
		return -1;
	}

	private int firstDateLine(String[] splits) {
		for (int i = 0; i < splits.length; i++) {
			if (splits[i].startsWith("===============")) {
				return i - 1;
			}
		}
		return -1;
	}

	private String nextHotel() {
		index = nextHotelLine(index);
		if (index < 0)
			return null;
		String s = StringUtils.replace(splits[index], "Hotel", "");
		int i = s.indexOf("Arr.");
		return s.substring(0, i - 1).trim();
	}

	private int nextHotelLine(int from) {
		for (int i = from; i < splits.length; i++) {
			if (splits[i].startsWith("Hotel")) {
				return i;
			}
		}
		return -1;
	}
}
